<!--
 * @Author: xiaxia
 * @Description: 
 * @Date: 2023-09-13 17:49:03
 * @LastEditTime: 2024-06-03 17:43:49
 * @FilePath: \vue-admin-template\src\components\issueInvioce\module\Payment .vue
-->
<template>
  <div>
    <el-card>
      <!-- 头部 -->
      <div class="header">
        <span class="title">发票清单</span>
        <div class="tagsC">
          <el-tag size="medium" v-show="payInfo.invoiceType=='2'" effect="plain" type="warning">纸质普票</el-tag>
          <el-tag size="medium" v-show="payInfo.invoiceType=='3'" effect="plain" type="warning">电子专票</el-tag>
          <el-tag size="medium" v-show="payInfo.invoiceType=='1'" effect="plain" type="warning">纸质专票</el-tag>
          <el-tag size="medium" v-show="payInfo.invoiceType=='4'" effect="plain" type="warning">电子普票</el-tag>
          <el-tag size="medium" v-show="payInfo.invoiceType=='5'" effect="plain" type="warning">外销发票</el-tag>
          <el-tag size="medium" v-show="payInfo.invoiceType=='I'" effect="plain" type="warning">数电纸专</el-tag>
          <el-tag size="medium" v-show="payInfo.invoiceType=='J'" effect="plain" type="warning">数电纸普</el-tag>
          <el-tag size="medium" v-show="payInfo.invoiceType=='K'" effect="plain" type="warning">数电专票</el-tag>
          <el-tag size="medium" v-show="payInfo.invoiceType=='L'" effect="plain" type="warning">数电普票</el-tag>
          <el-tag size="medium" v-show="payInfo.Business==1" effect="plain" type="info">建筑服务</el-tag>
          <el-tag size="medium" v-show="payInfo.Business==2" effect="plain" type="info">不动产销售</el-tag>
          <el-tag size="medium" v-show="payInfo.Business==3" effect="plain" type="info">不动产经营租赁服务</el-tag>
          <el-tag size="medium" v-show="payInfo.invoiceRed=='Y'" effect="plain">蓝字</el-tag>
          <el-tag size="medium" v-show="payInfo.invoiceRed=='X'" effect="plain" type="danger">红字</el-tag>
        </div>
      </div>

      <!-- 按钮 -->
      <div class="butC">
        <div>
          <el-button icon="el-icon-plus" type="primary" @click="addLine">增行</el-button>
          <el-popconfirm
            title="确定删除选中的开票信息吗？"
            style="margin-left: 15px"
            @confirm="toDel"
          >
            <el-button :disabled="tableSelect.length>0 ? false:true" type="info" slot="reference">删除</el-button>
          </el-popconfirm>
          <!-- <el-button disabled type="info">明细导入</el-button>
          <el-button disabled type="info">添加折扣</el-button> -->
          <el-switch
            v-model="isTax"
            active-text="含税"
            inactive-text="不含税"
            style="margin-left: 20px"
          >
          含税
          </el-switch>
        </div>
        <div>
          <!-- <el-button type="info">重选发票类型</el-button> -->
          <el-popconfirm
            title="确定清空已经填写开票信息吗？"
            style="margin-left: 15px"
            @confirm="toClear"
          >
            <el-button type="info" slot="reference">清空重填</el-button>
          </el-popconfirm>
        </div>
      </div>

      <!-- 表格 -->
      <div class="tableC">
        <el-table
          ref="multipleTable"
          :data="tableData"
          show-summary
          :summary-method="getSummaries"
          @selection-change="hSelectChange"
          row-key="index"
        >
          <el-table-column type="selection" width="45" align="center">
          </el-table-column>
          <el-table-column label="序号" width="60" prop="docLine">
            <template #default="scope">
              {{scope.row.docLine=scope.$index+1}}
              {{sumTax(scope.row)}}
            </template>
          </el-table-column>
          <el-table-column prop="itemName" label="项目名称" width="260" >
            <template #default="{row}">
              <div style="display: flex;">
                <el-input v-model="row.itemName" placeholder="请输入"></el-input>
                <el-button 
                  size="mini"
                  @click="showD(row)" 
                  icon="el-icon-more-outline"
                  style="margin-left: 5px; padding:7px 10px;"
                ></el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="taxCatecode" label="税收分类编码">
            <template #default="{row}">
              <el-input v-model="row.taxCatecode" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="itemSpec" label="规格型号">
            <template #default="{row}">
              <el-input v-model="row.itemSpec" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位">
            <template #default="{row}">
              <el-input v-model="row.unitName" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量">
            <template #default="{row}">
              <el-input v-model="row.quantity" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="zamountSej" label="税额">
            <template #default="{row}">
              <el-input disabled v-model="row.zamountSej" placeholder="请输入"></el-input>
              <!-- {{row.zamountSej}} -->
            </template>
          </el-table-column>
          <div v-if="isTax">
            <el-table-column prop="zpriceHsj" label="单价（含税）" min-width="100">
              <template #default="{row}">
                <el-input disabled v-model="row.zpriceHsj" placeholder="请输入"></el-input>
              </template>
            </el-table-column>
            <el-table-column  prop="zamountHsj" label="金额（含税）" min-width="100">
              <template #default="{row}">
                <!-- <el-input v-model="row.zamountHsj" placeholder="请输入"></el-input> -->
                <el-input-number 
                  v-model="row.zamountHsj" 
                  controls-position="right" 
                  :precision="2"
                ></el-input-number>
              </template>
            </el-table-column>
          </div>
          <div v-if="!isTax">
            <el-table-column prop="zpriceWsj" label="单价（不含税）" min-width="110">
              <template #default="{row}">
                <el-input disabled v-model="row.zpriceWsj" placeholder="请输入"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="zamountWsj" label="金额（不含税）" min-width="110">
              <template #default="{row}">
                <!-- <el-input v-model="row.zamountWsj" placeholder="请输入"></el-input> -->
                <el-input-number 
                  v-model="row.zamountWsj" 
                  controls-position="right" 
                  :precision="2"
                ></el-input-number>
              </template>
            </el-table-column>
          </div>
          <el-table-column prop="taxRate" label="税率/征收率">
            <template #default="{row}">
              <!-- <el-input v-model="row.taxRate" placeholder="请输入"></el-input> -->
              <el-select v-model="row.taxRate">
                <el-option
                  v-for="item in taxOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="jshj">
          <span>
            价税合计（大写）: {{ totalPrice|toChies}}
          </span>
          <span class="jshjX">
            价税合计（小写）: {{ totalPrice}}
          </span>
        </div>
        <el-divider></el-divider>
      </div>
      
      <!-- 红字信息部分 -->
      <div v-if="payInfo.invoiceRed=='X'">
        <div class="title2">
          <span >红字发票 - 红字信息</span>
        </div>
        <el-form 
          ref="redForm" 
          :rules="rules"
          :model="redForm"
          label-position="top"
        >
          <el-row :gutter="25">
            <el-col :span="5">
              <el-form-item label="蓝字发票代码" prop="invoiceRedFpdm">
                <el-input v-model="redForm.invoiceRedFpdm" placeholder="请输入（必填项）"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="蓝字发票号码" prop="invoiceRedFphm">
                <el-input v-model="redForm.invoiceRedFphm" placeholder="请输入（必填项）"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="蓝字开票日期" prop="invoiceRedKprq">
                <el-date-picker 
                  type="date" 
                  v-model="redForm.invoiceRedKprq" 
                  placeholder="选择日期（必填项）" 
                  style="width:100%"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="红字申请原因" prop="invoiceRedReqm">
                <el-select clearable v-model="redForm.invoiceRedReqm" placeholder="请选择（必填项）" style="width:100%">
                  <el-option label="购方申请" :value="11"></el-option>
                  <el-option label="销方申请" :value="21"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="红字申请单号" prop="invoiceRedXxbm">
                <el-input v-model="redForm.invoiceRedXxbm" placeholder="请输入（购方必填项）"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 特定信息 -->
      <!-- <Specific></Specific> -->
    </el-card>


    <!-- 选择 弹窗 -->
    <el-drawer
      title="项目信息分类"
      size="700px"
      :visible.sync="drawerShow"
    >
      <!-- 查询 -->
      <el-form inline :model="searchForm" status-icon label-width="100px" >
        <el-form-item label="项目名称" prop="itemName">
          <el-input v-model="searchForm.itemName" clearable></el-input>
        </el-form-item>
        <el-form-item label="税收分类编码" prop="itemSsflbm">
          <el-input v-model="searchForm.itemSsflbm" clearable></el-input>
        </el-form-item>
        <el-form-item label="规格型号" prop="itemSpec">
          <el-input v-model="searchForm.itemSpec" clearable></el-input>
        </el-form-item>
        <el-form-item label=" ">
          <el-button type="primary" @click="searchItem()">查询</el-button>
          <el-button @click="resetItem()">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table class="drawerC" :data="itemData">
        <el-table-column type="index" label="序号" width="50" show-overflow-tooltip fixed="left"></el-table-column>
        <el-table-column prop="itemName" label="项目名称" width="150" show-overflow-tooltip fixed="left"></el-table-column>
        <el-table-column prop="taxRate" label="税率" width="60" show-overflow-tooltip></el-table-column>
        <el-table-column prop="itemSsflbm" label="税收分类编码" width="140" show-overflow-tooltip></el-table-column>
        <el-table-column prop="itemSpec" label="规格型号" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="unitName" label="开票计量单位" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column fixed="right" label="操作" width="80">
        <template #default="{row}">
          <el-button
            @click="chooSell(row)"
            type="text"
            size="small">
            选择
          </el-button>
        </template>
      </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="hSizeChange"
        @current-change="hCurrentChange"
        :current-page="searchForm.pageNum"
        :page-sizes="[10, 15, 20]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="searchForm.rowCount">
      </el-pagination>
    </el-drawer>
  </div>
</template>
<script>
import Specific from "@/components/issueInvioce/module/Specific.vue";
export default {
  components:{Specific},
  data() {
    return{
      payInfo: {},
      tableData: [
        {
          docLine: '1', // 行号
          itemName: '', // 项目名称
          taxCatecode: '', // 税收分类编码
          itemSpec: '', // 规格型号
          unitName: '', // 单位
          quantity: '', // 数量
          zpriceWsj: '', // 单价（不含税）
          zamountWsj: '', // 金额（不含税）
          zpriceHsj: '', // 单价（含税）
          zamountHsj: '', // 金额（含税）
          taxRate: '0', // 税率/征收率
          zamountSej: '', // 税额
        }
      ],
      tableSelect: [], // 表格选中数据
      totalPrice: '', // 价税合计
      noTaxPrince: '', // 金额
      totalTax: '', // 税额
      isTax: true, // 含税不含税
      taxOptions:[
        { label: '0%', value: 0},
        { label: '6%', value: 0.06},
        { label: '9%', value: 0.09},
        { label: '13%', value: 0.13},
      ],
      redForm: {
        invoiceRedFpdm: '', //蓝字发票代码
        invoiceRedFphm: '', //蓝字发票号码
        invoiceRedKprq: '', //蓝字开票日期
        invoiceRedReqm: '', //红字申请原因 11:购方申请 21:销方申请
        invoiceRedXxbm: '', //红字申请单号
      },
      drawerShow: false, // 弹窗
      rules: {
        invoiceRedFphm: [
          { required: true, message: '请输入蓝字发票号码', trigger: 'blur' }
        ],
        invoiceRedKprq: [
          { required: true, type: 'date', message: '请选择蓝字开票日期', trigger: 'change' }
        ],
        invoiceRedReqm: [
          { required: true, message: '请选择红字申请原因', trigger: 'change' }
        ],
      },
      chooseLine: {}, // 当前选择行  项目名称
      searchForm: {
        itemName: '', // 项目名称
        itemSsflbm: '', //税收分类编码
        itemSpec: '' , // 规格型号
        pageSize: 10,
        pageNum: 1,
        rowCount: 0,
      },
      itemData: [],
    }
  },
  methods:{
    // 增行
    addLine() {
      console.log(this.tableData.find(item => item.itemName != '' && item.zamountWsj != ''));
      this.tableData.push(
        {
          docLine: this.tableData.length+1, // 行号
          itemName: '', // 项目名称
          itemSpec: '', // 规格型号
          unitName: '', // 单位
          quantity: '', // 数量
          zpriceWsj: '', // 单价（不含税）
          zamountWsj: '', // 金额（不含税）
          zpriceHsj: '', // 单价（含税）
          zamountHsj: '', // 金额（含税）
          taxRate: '0', // 税率/征收率
          zamountSej: '', // 税额
        }
      )
    },
    // 删除
    toDel() {
      if(this.tableData.length <= 1) return this.$message.error('仅剩一条开票信息，无法删除！')
      this.tableSelect.forEach(it => {
        let i = this.tableData.findIndex(item => item.docLine == it.docLine)
        if(i != -1) this.tableData.splice(i, 1)
      })
      this.tableSelect = []
      this.$refs.multipleTable.clearSelection();
      console.log(this.tableSelect, '选中要删除的数据1111');
      this.isTax = false
    },
    // 清空重填
    toClear() {
      this.tableData = [
        {
          docLine: '1', // 行号
          itemName: '', // 项目名称
          itemSpec: '', // 规格型号
          unitName: '', // 单位
          quantity: '', // 数量
          zpriceWsj: '', // 单价（不含税）
          zamountWsj: '', // 金额（不含税）
          zpriceHsj: '', // 单价（含税）
          zamountHsj: '', // 金额（含税）
          taxRate: '0', // 税率/征收率
          zamountSej: '', // 税额
        }
      ]
    },
    // 表格选中
    hSelectChange(val) {
      this.tableSelect = val
    },
    // 计算税额 金额
    sumTax(row){
      if(this.isTax) { // 1. true含税 
        if(row.zamountHsj!=0){
          row.zamountSej = Number((row.zamountHsj*row.taxRate)/(1+Number(row.taxRate))).toFixed(2) // 税额
          row.zamountWsj = (Number(row.zamountHsj)-Number(row.zamountSej)).toFixed(2) // 金额（不含税）
          if(row.quantity!=0) {
            row.zpriceHsj = (row.zamountHsj/row.quantity).toFixed(8) // 单价（含税）
          }
        }
      } else { // 2. false不含税
        if(row.zamountWsj!=0) {
          row.zamountSej = (row.zamountWsj*row.taxRate).toFixed(2) // 税额
          row.zamountHsj = (Number(row.zamountSej)+Number(row.zamountWsj)).toFixed(2) // 金额（含税）
          if(row.quantity!=0) {
            row.zpriceWsj = (row.zamountWsj/row.quantity).toFixed(8) // 单价（不含税）
          }
        }
      }
    },

    // 查询 项目信息
    async searchItem() {
      // const { data: res } = await getItems(this.searchForm)
      // if(!res.success) return this.$message.error('查询项目信息失败！'+res.msg)
      // this.itemData = res.data.items
      // this.searchForm.rowCount = res.data.rowCount
    },
    showD(row) {
      this.searchItem()
      this.drawerShow = true
      this.chooseLine = row // 当前选择行 项目名称
    },
    // 选择
    chooSell(row){
      this.tableData.forEach(item => {
        if(item.docLine == this.chooseLine.docLine){
          item.itemName = row.itemName
          item.taxCatecode = row.itemSsflbm
          item.itemSpec = row.itemSpec
          item.unitName = row.unitName
          item.taxRate = Number(row.taxRate)
        }
      })
      this.drawerShow = false
    },
    resetItem() {
      this.searchForm = {
        itemName: '', // 项目名称
        itemSsflbm: '', //税收分类编码
        itemSpec: '' , // 规格型号
        pageSize: 10,
        pageNum: 1,
        rowCount: 0,
      }
      this.searchItem()
    },
    hSizeChange(size) {
      this.searchForm.pageSize = size
      this.searchItem()
    },
    hCurrentChange(num) {
      this.searchForm.pageNum = num
      this.searchItem()
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        const values = data.map(item => Number(item[column.property]))

        if(this.isTax) { // 1. 含税
          if (column.property == 'zamountHsj' ) { // 1. 含税 
            this.TaxPrince = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else if(column.property == 'zamountSej') { // 2 .税额
            this.totalTax = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = '￥'+this.totalTax.toFixed(2)
            sums[9] = '￥'+(this.TaxPrince-this.totalTax).toFixed(2) // 3.不含税
            this.noTaxPrince = sums[9] // 3.不含税
            console.log(this.noTaxPrince, '1111111111');
            this.totalPrice  = this.TaxPrince.toFixed(2) // 4. 含税
          } else {
            sums[index] = '';
          }
        } else { // 2. 不含税
          if (column.property == 'zamountWsj' ) { // 1. 不含税 
            this.noTaxPrince = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else if(column.property == 'zamountSej') { // 2 .税额
            this.totalTax = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[9] = '￥'+this.noTaxPrince.toFixed(2)
            sums[index] = '￥'+this.totalTax.toFixed(2)
            this.totalPrice  = (this.noTaxPrince+this.totalTax).toFixed(2) // 3. 含税
          } else {
            sums[index] = '';
          }
        }

        
      });
      return sums;
    }
  },
  filters: { //局部过滤器
    toChies: function(amount) { //形参
      // 汉字的数字
      const cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
      // 基本单位
      const cnIntRadice = ["", "拾", "佰", "仟"];
      // 对应整数部分扩展单位
      const cnIntUnits = ["", "万", "亿", "兆"];
      // 对应小数部分单位
      const cnDecUnits = ["角", "分"];
      // 整数金额时后面跟的字符
      const cnInteger = "整";
      // 整型完以后的单位
      const cnIntLast = "元";
      // 最大处理的数字
      const maxNum = 9999999999999999.99;
      // 金额整数部分
      let integerNum;
      // 金额小数部分
      let decimalNum;
      // 输出的中文金额字符串
      let chineseStr = "";
      // 分离金额后用的数组，预定义
      let parts;
      if (amount === "") {
        return "";
      }
      amount = parseFloat(amount);
      if (amount >= maxNum) {
        // 超出最大处理数字
        return "";
      }
      if (amount === 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
      }
      // 转换为字符串
      amount = amount.toString();
      if (amount.indexOf(".") === -1) {// 1. 不是小数
        integerNum = amount;

        decimalNum = "";
      } else { // 2. 是小数
        parts = amount.split(".");
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
      }
      // 获取整型部分转换
      if (parseInt(integerNum, 10) > 0) {// 1.正数
        let zeroCount = 0;
        const IntLen = integerNum.length;
        for (let i = 0; i < IntLen; i++) {
          const n = integerNum.substr(i, 1);
          const p = IntLen - i - 1;
          const q = p / 4;
          const m = p % 4;
          if (n === "0") {
              zeroCount++;
          } else {
            if (zeroCount > 0) {
                chineseStr += cnNums[0];
            }
            // 归零
            zeroCount = 0;
            //alert(cnNums[parseInt(n)])
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m === 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        chineseStr += cnIntLast;
      } else{ // 2. 负数
        integerNum = Math.abs(integerNum).toString() // 负数转正数
        let zeroCount = 0;
        const IntLen = integerNum.length;
        for (let i = 0; i < IntLen; i++) {
          const n = integerNum.substr(i, 1);
          const p = IntLen - i - 1;
          const q = p / 4;
          const m = p % 4;
          if (n === "0") {
              zeroCount++;
          } else {
            if (zeroCount > 0) {
                chineseStr += cnNums[0];
            }
            // 归零
            zeroCount = 0;
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m === 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        console.log(chineseStr, cnIntLast, '2负数-------------');
        chineseStr = '（负数）' + chineseStr + cnIntLast;
      }
      // 小数部分
      if (decimalNum !== "") {
        const decLen = decimalNum.length;
        for (let i = 0; i < decLen; i++) {
          const n = decimalNum.substr(i, 1);
          if (n !== "0") {
              chineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
      if (chineseStr === "") {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
      } else if (decimalNum === "") {
        chineseStr += cnInteger;
      }
      return chineseStr;
    }
  },
}
</script>

<style lang="scss" scoped>
.header{
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .title{
    font-size: 17px;
    font-weight: 700;
  }
  .tagsC{
    margin-left: 10px;
  }
}
.title2{
  font-size: 18px;
  font-weight: 700;
  margin: 30px 0 10px 0;
}
.butC{
  display: flex;
  justify-content: space-between;
}
.tableC {
  margin-top: 15px;
}
.jshj{
  display: flex;
  justify-content: flex-end;
  align-items: center;
  width: 100%;
  height: 42px;
  line-height: 42px;
  font-weight: 600;
  font-size: 14px;

  .jshjX{
    margin-left: 50px;
  }
}
.drawerC{
  padding: 0 20px;
}
::v-deep{
  .el-table__footer-wrapper tbody td.el-table__cell{
    background-color: #fff;
  }
  .el-divider{
    margin: 0;
  }

  .el-input-number.is-controls-right {
    width: 100%;
    .el-input-number__decrease{
      height: 0;
    }
    .el-input-number__increase{
      height: 0;
    }
    .el-icon-arrow-up{
      font-size: 0;
    }
    .el-input__inner{
      text-align: left;
      padding-right: 15px;
    }
  }
  
}
</style>